/**
 * 
 */
package com.jiang.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * @author Administrator
 *
 */
public class XMLUpdate {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{

		File file = new File("books.xml");
		InputStream is = new FileInputStream(file);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document document = db.parse(is);
		Map<String,String> auths = new HashMap<String,String>();
		auths.put("水浒传", "施耐庵");
		auths.put("红楼梦", "曹雪芹");
		auths.put("西游记", "吴承恩");

		// 对每个子元素添加出版社pub节点和真实作者。
		NodeList bookList = document.getElementsByTagName("book");
		for(int i=0;i<bookList.getLength();i++){
			Element bookEle = (Element)bookList.item(i);
			Element pubEle = document.createElement("pub");
			pubEle.setTextContent("人民教育出版社");
			bookEle.appendChild(pubEle);
			Element authEle = document.createElement("auth");
			String bookName = bookEle.getElementsByTagName("name").item(0).getTextContent();
			authEle.setTextContent(auths.get(bookName));
			bookEle.appendChild(authEle);
		}
		// 2. 使用transform类输出
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		DOMSource ds = new DOMSource(document);
		//设置编码
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		Result result = new StreamResult(file);
		transformer.transform(ds, result);
	}

}
